package org.eden.web.service;

import org.eden.rpc.common.entity.dao.User;
import org.eden.web.pojo.Response;
import org.eden.web.pojo.States;
import org.eden.web.utils.JWTUtil;

public abstract class AbstractLoginService implements LoginService {

    @Override
    public Response login(User user, String req) {
        User byUsername = findByUsername(user.getUsername());
        if (byUsername == null) {
            return new Response(States.USER_NOT_FOUND);
        }
        if (!checkStatus(byUsername)) {
            return new Response(States.LOGIN_FAILED);
        }
        if (checkAccess(byUsername, req)) {
            String token = JWTUtil.createToken(byUsername);
            return new Response(States.LOGIN_SUCCESS.getCode(), token);
        }
        return new Response(States.LOGIN_FAILED);
    }

    abstract public boolean checkAccess(User user, String req);

    public User findByUsername(String username) {
        // 模拟调用rpc
        User user = new User();
        user.setUsername(username);
        user.setId(1L);
        user.setPassword("$2a$10$72xqIbYF4yeQ0aMQBAXdoeiM9F851A7cA37t1gk.Rn7dtoa6eHR6e"); // 1234的编码结果
        if ("zka".equals(username)) {
            user.setAuthority("admin");
        } else {
            user.setAuthority("guest");
        }
        return user;
    }

    public boolean checkStatus(User user) {
        // 检查用户是否被禁止登陆、用户是否
        return true;
    }
}
